<?php

namespace common\extensions\rsa;

use Exception;
use Yii;

/**
 * 非对称加解密：公钥加密，私钥解密
 */
class Rsa
{
    /**
     * @desc 公钥加密
     * @return string 需要加密的字符串
     * @Date: 2024/11/4
     * @throws Exception
     */
    public static function encrypt($string): string
    {
        $selfObj = new Rsa();
        // 获取 公钥
        $key = openssl_pkey_get_public($selfObj->getRsaPublic());
        if (!$key) {
            throw new Exception('公钥不可用');
        }
        // 公钥加密
        $return_en = openssl_public_encrypt($string, $encrypted, $key);
        if (!$return_en) {
            throw new Exception('加密失败,请检查RSA秘钥');
        }
        return base64_encode($encrypted);
    }


    /**
     * @desc 需要解密的字符串
     * @return string
     * @Date: 2024/11/4
     * @throws Exception
     */
    public static function decrypt($string): string
    {
        $selfObj = new Rsa();
        // 获取 私钥
        $private_key = openssl_pkey_get_private($selfObj->getRsaPrivate());
        if (!$private_key) {
            throw new Exception('私钥不可用');
        }
        // 私钥解密
        $return_de = openssl_private_decrypt(base64_decode($string), $decrypted, $private_key);
        if (!$return_de) {
            throw new Exception('解密失败,请检查RSA秘钥');
        }
        return $decrypted;
    }

    /**
     * @desc 需要解密的字符串
     * @return string
     * @Date: 2024/11/4
     * @throws Exception
     */
    public static function decryptJsEncrypt($string): string
    {
        $selfObj = new Rsa();
        // 获取 私钥
        $private_key = openssl_pkey_get_private($selfObj->getRsaPrivate());
        if (!$private_key) {
            throw new Exception('私钥不可用');
        }
        $encrypt_data = pack("H*", $string);//对十六进制数据进行转换
        $return_de = openssl_private_decrypt($encrypt_data, $decrypted, $private_key);
        if (!$return_de) {
            throw new Exception('解密失败,请检查RSA秘钥');
        }
        return $decrypted;
    }

    private function getRsaPublic()
    {
        return file_get_contents(Yii::getAlias('@common')
            . DIRECTORY_SEPARATOR . 'extensions'
            . DIRECTORY_SEPARATOR . 'rsa'
            . DIRECTORY_SEPARATOR . 'keys'
            . DIRECTORY_SEPARATOR . 'publicKey.txt');
    }

    private function getRsaPrivate()
    {
        return file_get_contents(Yii::getAlias('@common')
            . DIRECTORY_SEPARATOR . 'extensions'
            . DIRECTORY_SEPARATOR . 'rsa'
            . DIRECTORY_SEPARATOR . 'keys'
            . DIRECTORY_SEPARATOR . 'privateKey.txt');
    }
}
